import { useFindCommentInfoByGoods, useFindCommentList } from "@/apis/goods";
import "./index.scss";
import { Fragment, useContext, useEffect, useState } from "react";
import { GoodsContext } from "../../index";
import classNames from "classnames";
import GoodsCommentImage from "../GoodsCommentImage";
import XtxPagination from "@/components/library/xtxPagination";
function GoodsComment() {
  const goods = useContext(GoodsContext);
  const { result } = useFindCommentInfoByGoods(goods?.id);
  const [commentInfo, setCommentInfo] = useState<any>();
  const [currentIndex, setIndex] = useState(0);
  const [reqParams, setParams] = useState<any>({
    page: 1,
    pageSize: 10,
    hasPicture: null,
    tag: null,
    sortField: null,
  });
  const { result: commenRes } = useFindCommentList(goods?.id, reqParams);
  const [commenList, setCommentList] = useState([]);
  const [total, setTotal] = useState(0);

  const changeSort = function (type: string | null) {
    setParams({
      ...reqParams,
      sortField: type,
      page: 1,
    });
  };
  const changeTag = function (type: number) {
    setIndex(type);
    const tagType = commentInfo.tags[type].type;
    const newParams = { ...reqParams };
    if (tagType === "all") {
      newParams.hasPicture = null;
      newParams.tag = null;
    } else if (tagType === "img") {
      newParams.hasPicture = true;
      newParams.tag = null;
    } else {
      newParams.hasPicture = null;
      newParams.tag = commentInfo.tags[type].title;
    }
    setParams({ ...newParams, page: 1 });
  };
  const formatNickname = function (nickname: string) {
    return nickname;
  };
  const formatSpecs = function (val: any) {
    return val.reduce(
      (pre: any, cur: any) => `${pre} ${cur.name} ${cur.nameValue}`,
      ""
    );
  };

  useEffect(() => {
    if (result) {
      result.tags.unshift({
        type: "img",
        title: "有图",
        tagCount: result.hasPictureCount,
      });
      result.tags.unshift({
        type: "all",
        title: "全部评价",
        tagCount: result.evaluateCount,
      });
      setCommentInfo(result);
    }
  }, [result]);

  useEffect(() => {
    setCommentList(commenRes?.items);
    setTotal(commenRes?.counts);
  }, [commenRes, commenRes?.counts]);
  const changePage = function (callback: string, current: number) {
    setParams({ ...reqParams, page: current });
  };
  return (
    <>
      {commentInfo && (
        <div className="goods-comment">
          <div className="head">
            <div className="data">
              <p>
                <span>{commentInfo.salesCount}</span>
                <span>人购买</span>
              </p>
              <p>
                <span>{commentInfo.praisePercent}</span>
                <span>好评率</span>
              </p>
            </div>
            <div className="tags">
              <div className="dt">大家都在说：</div>
              <div className="dd">
                {commentInfo.tags.map((item: any, i: number) => (
                  <a
                    href="javascript:;"
                    className={classNames({ active: currentIndex === i })}
                    onClick={() => changeTag(i)}
                  >
                    {item.title}（{item.tagCount}）
                  </a>
                ))}
              </div>
            </div>
          </div>
          <div className="sort">
            <span>排序：</span>
            <a
              href="javascript:;"
              className={classNames({ active: reqParams.sortField === null })}
              onClick={() => changeSort(null)}
            >
              默认
            </a>
            <a
              href="javascript:;"
              className={classNames({
                active: reqParams.sortField === "createTime",
              })}
              onClick={() => changeSort("createTime")}
            >
              最新
            </a>
            <a
              href="javascript:;"
              className={classNames({
                active: reqParams.sortField === "praiseCount",
              })}
              onClick={() => changeSort("praiseCount")}
            >
              最热
            </a>
          </div>
          {commenList && (
            <div className="list">
              {commenList.map((item: any) => (
                <div className="item" key={item.id}>
                  <div className="user">
                    <img src={item.member.avatar} alt="" />
                    <span>{formatNickname(item.member.nickname)}</span>
                  </div>

                  <div className="body">
                    <div className="score">
                      {Array.from({ length: item.score }, (v, i) => i).map(
                        (item, index) => (
                          <Fragment key={index}>
                            {/* 确保这里渲染的是 JSX 或者字符串，而不是一个对象 */}
                            <i className="iconfont icon-wjx01"></i>
                          </Fragment>
                        )
                      )}
                      {Array.from({ length: 5 - item.score }, (v, i) => i).map(
                        (item, index) => (
                          <Fragment key={index}>
                            {/* 确保这里渲染的是 JSX 或者字符串，而不是一个对象 */}
                            <i className="iconfont icon-wjx02"></i>
                          </Fragment>
                        )
                      )}
                      <span className="attr">
                        {formatSpecs(item.orderInfo.specs)}
                      </span>
                    </div>

                    <div className="text">{item.content}</div>
                    {item.pictures.length && (
                      <GoodsCommentImage
                        pictures={item.pictures}
                      ></GoodsCommentImage>
                    )}

                    <div className="time">
                      <span>{item.createTime}</span>
                      <span className="zan">
                        <i className="iconfont icon-dianzan"></i>
                        {item.praiseCount}
                      </span>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
          {total > 0 && (
            <XtxPagination
              total={total}
              currentPage={reqParams.page}
              emit={changePage}
            ></XtxPagination>
          )}
        </div>
      )}
    </>
  );
}
export default GoodsComment;
